<template>
  <base-breadcrumb>
    <div
      v-loading="loading[0] || loading[1]"
      class="about-master-container"
    >
      <a-card :bordered="false">
        <title-name title="科技成果申报信息" />
        <a-form-model
          ref="form"
          :model="queryParam"
          :rules="rules"
        >
          <a-row>
            <a-col span="16">
              <a-form-model-item
                label="所属单位"
                prop="projectId"
              >
                <org-tree-select
                  v-model="queryParam.projectId"
                  :form="queryParam"
                  :is-auto-select-first="type !== 'edit'"
                  is-need-auth
                  check-strictly
                  @select="selectOrg"
                />
              </a-form-model-item>
            </a-col>
            <!--            <a-col span="8">-->
            <!--              <a-form-model-item-->
            <!--                label="所属分公司"-->
            <!--                prop="branchCompanyId"-->
            <!--              >-->
            <!--                <SelectSubCompany placeholder="请选择"-->
            <!--                                  v-model="queryParam.branchCompanyId"-->
            <!--                                  :autoSelected="type !== 'edit'"-->
            <!--                ></SelectSubCompany>-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <!--            <a-col span="8">-->
            <!--              <a-form-model-item-->
            <!--                label="项目名称"-->
            <!--                prop="projectId"-->
            <!--              >-->
            <!--                <SelectProject placeholder="请选择"-->
            <!--                               v-model="queryParam.projectId"-->
            <!--                               :form="queryParam"-->
            <!--                               :is-edit="type === 'edit'"-->
            <!--                               keyValue="branchCompanyId"-->
            <!--                ></SelectProject>-->
            <!--              </a-form-model-item>-->
            <!--            </a-col>-->
            <a-col span="8">
              <a-form-model-item
                label="成果名称"
                prop="declareAchievementsName"
              >
                <BaseInput
                  v-model="queryParam.declareAchievementsName"
                  placeholder="请输入申报成果名称"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item
                label="成果分类"
                prop="declareAchievementsTypeId"
              >
                <a-select
                  v-model="queryParam.declareAchievementsTypeId"
                  placeholder="请选择"
                  @change="getLevelList($event)"
                >
                  <a-select-option
                    v-for="item in ClassifyList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{
                      item.name
                    }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item
                label="成果等级"
                prop="declareAchievementsLevelId"
              >
                <a-select
                  v-model="queryParam.declareAchievementsLevelId"
                  placeholder="请选择"
                  @change="completeAchievementsLevelIdChange($event)"
                >
                  <a-select-option
                    v-for="i in LevelList"
                    :key="i.id"
                    :value="i.id"
                  >
                    {{ i.levelName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item
                ref="name"
                label="申报人"
                prop="joinEmployee"
                :auto-link="false"
              >
                <a-tag
                  v-for="item in queryParam.joinEmployee"
                  :key="item.id"
                  closable
                  @blur="() => {$refs.name.onFieldBlur()}"
                  @close="queryParam.joinEmployee = queryParam.joinEmployee.filter((v) => v.id !== item.id)"
                >
                  {{ item.name }}
                </a-tag>
                <a-button
                  v-if="queryParam.joinEmployee.length < canAddPeopleLength"
                  style="margin-right: 10px"
                  :disabled="!completeAchievementsLevelName1"
                  @click="visible = true"
                >
                  添加
                </a-button>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item
                prop="declareDate"
                label="申报日期"
              >
                <a-date-picker
                  v-model="queryParam.declareDate"
                  type="date"
                  @change="getDeclareDate"
                />
              </a-form-model-item>
            </a-col>
            <a-col span="24">
              <a-form-model-item
                ref="fileArrays"
                label="附件"
                prop="fileArrays"
                :auto-link="false"
              >
                <upload-list
                  :is-limit="true"
                  business-code="STM04"
                  :upload-arrys.sync="queryParam.fileArrays"
                />
              </a-form-model-item>
              <span
                class="del_btn"
                style="margin-left: 100px;"
              >上传提示：需上传终稿申报资料</span>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <div class="page-btn-right-top">
        <a-button
          v-if="(type == 'edit' && (status == '9' || status == '3'|| status == '0')) || type == 'add'"
          :loading="loading[0]"
          :disabled="loading[1]"
          type="primary"
          class="btn_right"
          @click="submitDeclare(0)"
        >
          {{ status == '3' ? '保存' : '保存草稿' }}
        </a-button>
        <a-button
          v-if="(type == 'edit' && (status == '9' || status == '3'|| status == '0')) || type == 'add'"
          :loading="loading[1]"
          :disabled="loading[0]"
          type="primary"
          class="btn_right"
          @click="submitDeclare(1)"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="$close"
        >
          关闭
        </a-button>
      </div>
    </div>
    <SelectPerson
      :max-select-length="canAddPeopleLength"
      :visible.sync="visible"
      title="添加完成人"
      :list.sync="queryParam.joinEmployee"
    />
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>

<script>
import { getClassifyList, getGradeList } from '@/api/achievementsType'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import UploadList from '@/components/UploadList'
import { addDeclare, removeDeclare, editDeclare, getDeclare } from '@/api/achievementsManage'
import BaseEditPage from '@/views/baseEditPage'
import SelectPerson from '@/components/Select/SelectPerson'

const rules = {
  branchCompanyId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
  projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
  declareAchievementsName: [{ required: true, message: '请输入申报成果名称', trigger: 'change' }],
  declareAchievementsTypeId: [{ required: true, message: '请选择申报分类', trigger: 'change' }],
  declareCompleteEmployee: [{ required: true, message: '请输入申报完成人', trigger: 'change' }],
  declareAchievementsLevelId: [{ required: true, message: '请选择成果等级', trigger: 'change' }],
  declareDate: [{ required: true, message: '请选择申报日期', trigger: 'change' }],
  fileArrays: [{ type: 'array', required: true, message: '请上传附件', trigger: 'change' }],
  joinEmployee: [{ type: 'array', required: true, message: '请选择申报人', trigger: 'change' }]
}
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    UploadList,
    SelectSubCompany,
    SelectProject,
    SelectPerson
  },
  data() {
    return {
      loading: { 0: false, 1: false },
      queryParam: {
        joinEmployee: [],
        fileArrays: [],
        branchCompanyId: '',
        projectId: ''
      },
      rules: rules,
      branchCompanyList: [],
      declareDate: undefined,
      objectList: [],
      ClassifyList: [],
      LevelList: [],
      visible: false,
      removeApi: { remove: removeDeclare },
      confirmLoading: false,
      planRange: false,
      title: undefined,
      double: false,
      status: '9',
      updataPersonnes: [],
      achievementsTypeName: '',
      completeAchievementsLevelName1: '',
      init: false,
     //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    canAddPeopleLength() {
      if (this.achievementsTypeName === '研发立项' || this.achievementsTypeName === '示范工程立项') {
        if (this.completeAchievementsLevelName1.includes('局') || this.completeAchievementsLevelName1.includes('省')) {
          return 15
        }
      }
      return 100
    }
  },
  watch: {
    'queryParam.joinEmployee'(newVal, oldVal) {
      if (this.init && newVal !== oldVal) {
        this.$refs.form.validateField('joinEmployee')
      }
    },
    'queryParam.fileArrays'(newVal, oldVal) {
      if (this.init) {
        this.$refs.fileArrays.onFieldChange()
      }
    }
  },
 async created() {
    this.getData()
        //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('achievements_declare')
  },
  methods: {
    selectOrg(val) {
      if(val.length>1) {
        this.form.branchCompanyId = val[val.length - 2].orgId
      }
    },
    async getData() {
      this.planRange = this.$route.query.planRange
      let res = await getClassifyList({ status: 1 })
      if (res.code === this.SUCCESS_CODE) {
        this.ClassifyList = res.data
      }
      if (this.type === 'edit') {
        this.loading[0] = true
        let res1 = await getDeclare({ declareId: this.id })
        this.loading[0] = false
        if (res1.code === this.SUCCESS_CODE) {
          this.queryParam = this.$assign(this.queryParam, res1.data.sciencesDeclare)
          this.queryParam.projectId = res1.data.projectId
          this.queryParam.branchCompanyId = res1.data.branchCompanyId
          this.status = res1.data.status
          if (this.queryParam.joinEmployee) {
            this.queryParam.joinEmployee = this.queryParam.joinEmployee.map(v => {
              return { name: v.employeeName, id: v.employeeId }
            })
          }
          this.queryParam.declareAchievementsTypeId && await this.getLevelList(this.queryParam.declareAchievementsTypeId, true)
          this.queryParam.declareAchievementsLevelId && this.completeAchievementsLevelIdChange(this.queryParam.declareAchievementsLevelId, true)
        }
      }
      setTimeout(() => {
        this.init = true
      }, 100)
    },
    getDeclareDate(data, dateString) {
      this.queryParam.declareDate = dateString
    },
    async getLevelList(id, init = false) {
      if (!init) {
        this.$set(this.queryParam, 'declareAchievementsLevelId', undefined)
      }
      let temp = this.ClassifyList.find(v => v.id === id)
      if (temp) {
        this.achievementsTypeName = temp.name
      }
      let res = await getGradeList({ typeId: this.queryParam.declareAchievementsTypeId, status: 1 })
      if (res.code === this.SUCCESS_CODE) {
        this.LevelList = res.data.data
      }
    },
    completeAchievementsLevelIdChange(e, init = false) {
      let temp = this.LevelList.find(v => v.id === e)
      if (temp) {
        this.completeAchievementsLevelName1 = temp.levelName
        if (!init) {
          this.queryParam.joinEmployee = []
        }
      }
    },
    handleChange(info) {
      if (info.file.status != 'uploading' && info.file.status != 'error') {
        this.queryParam.declareAttach = info.fileList.filter((item) => item.status == 'done')
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully`)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败.`)
      }
    },
    async submitDeclare(status) {
      this.setProcessConfig = null;
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('信息不完整')
          return false
        } else {
          if (status === 1) {
            this.submitApprovalConfirm(this.processConfig, async (flag) => {
              if(!flag) {
                return
              }
              this.queryParam.planOrNot = 0
              let queryParam = this.$clone(this.queryParam)
              queryParam.joinEmployee = this.queryParam.joinEmployee.map(v => {
                return { employeeName: v.name, employeeId: v.id }
              })
              queryParam.status = this.status == 3 && status == 0 ? this.status : status == 0 ? this.status : status
              this.loading[status] = true
              let url = { edit: editDeclare, add: addDeclare }[this.type]
              let res = await url(queryParam)
              this.loading[status] = false
              if (res.code === this.SUCCESS_CODE) {
                this.$message.success(['保存', '提交'][status] + '成功')
                 if(status*1===1) {
               //提交时，返回id
                  this.businessId = res.data.id;
                  this.setProcessConfig = this.processConfig;
                  return
              }else{
                this.$multiTab.close()
                }
              }
            })
          } else {
            this.queryParam.planOrNot = 0
            let queryParam = this.$clone(this.queryParam)
            queryParam.joinEmployee = this.queryParam.joinEmployee.map(v => {
              return { employeeName: v.name, employeeId: v.id }
            })
            queryParam.status = this.status == 3 && status == 0 ? this.status : status == 0 ? this.status : status
            this.loading[status] = true
            let url = { edit: editDeclare, add: addDeclare }[this.type]
            let res = await url(queryParam)
            this.loading[status] = false
            if (res.code === this.SUCCESS_CODE) {
              this.$message.success(['保存', '提交'][status] + '成功')
                if(status*1===1) {
               //提交时，返回id
                  this.businessId = res.data.id;
                  this.setProcessConfig = this.processConfig;
                  return
              }else{
                this.$multiTab.close()
                }
            }
          }

        }
      })
    }
  }
}
</script>
